package chances.system.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import chances.system.operator.entity.EnumData;
import chances.system.operator.repo.EnumDataRepository;

@Service
public class EnumService {
    @Autowired
    EnumDataRepository enumDataRepository;
    @Autowired
    EntityManagerFactory entityManagerFactory;

    public Map<String, String> getEnumMap(String code) {
        EnumData enumData = enumDataRepository.getByCode(code);
        List<EnumData> childs = enumDataRepository.findByParentId(enumData.getId());
        Map<String, String> result = childs.stream()
                .collect(Collectors.toMap(EnumData::getValue, EnumData::getName));
        return result;
    }

    @SuppressWarnings("unchecked")
    public List<EnumData> getEnumList(String code) {
        List<EnumData> result = null;
        EnumData enumData = enumDataRepository.getByCode(code);
        if (enumData.getType() == EnumData.TYPE_TEXT) {
            result = enumDataRepository.findByParentId(enumData.getId());
        } else if (enumData.getType() == EnumData.TYPE_HQL) {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            Query query = entityManager.createQuery(enumData.getValue());
            result = new ArrayList<EnumData>();
            List<Object[]> resultList = query.getResultList();
            for (Object[] objects : resultList) {
                EnumData eData = new EnumData();
                eData.setValue(objects[0].toString());
                eData.setName(objects[1].toString());
                result.add(eData);
            }
        }
        return result;
    }
}
